import * as ts from 'typescript';

import { apply } from '../plugins';
import tmpl from '../template';
import * as G from './generate';
import logger from './logger';

const fs = require('fs');
const path = require('path');

export function outputFileSync (file: string, c: string) {
	const dir = path.dirname(file);

	if (fs.existsSync(file)) {
		fs.writeFileSync(file, c);
	} else {
		fs.mkdirSync(dir, {
			mode: 0o777,
			recursive: true
		});
		fs.writeFileSync(file, c);
	}
}

export function generate (data: SwaggerSpec, Generate2dts: GenerateFn) {
	const file = ts.createSourceFile('_.d.ts', '', ts.ScriptTarget.Latest, false, ts.ScriptKind.TS);

	const content = Generate2dts(data);
	Object.assign(file, { statements: ts.factory.createNodeArray(content) });

	// 转换 AST
	const result = ts.transform(file, apply());

	// 由 AST 生成代码
	return ts.createPrinter().printFile(result.transformed[0]);
}

export function GenerateInterface2dts (data: SwaggerSpec) {
	return data?.definitions ? generate(data, G.GenerateInterface2dts) : '';
}

export function GenerateAPI2dts (data: SwaggerSpec) {
	return data?.paths ? generate(data, G.GenerateAPI2dts) : '';
}

export function GenerateTypeAlias2dts (data: SwaggerSpec) {
	return data?.definitions ? generate(data, G.GenerateTypeAlias2dts) : '';
}

/**
 * Notes - Generate Aixos Methods
 * @param file string
 * @returns void
 */
export async function GenerateAxios2dts (file: string) {
	const cwd = process.cwd();
	const https = path.resolve(cwd, file);
	if (fs.existsSync(https)) return;
	try {
		outputFileSync(https, tmpl.trim());
	} catch (error) {
		logger.error(error);
	}
}